package com.ld.security.server.user.modules.rec.util;

import com.ld.security.common.core.base.ESuperEntity;
import com.ld.security.common.core.exception.ApiException;
import com.ld.security.server.user.modules.rec.conver.RecItemConver;
import com.ld.security.server.user.modules.rec.entity.RecItemEntity;
import com.ld.security.server.user.modules.rec.service.IRecItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.CompletableFuture;

@Component
public class RecUtil {

    private static List<RecItemConver> list;

    private static IRecItemService iRecItemService;

    public static boolean hasItemConver(Class clazz){
        for (RecItemConver recItemConver : list) {
            if(recItemConver.getEntityClass().equals(clazz)){
                return true;
            }
        }
        return false;
    }

    private static RecItemConver getRecItemConver(ESuperEntity obj){
        for (RecItemConver recItemConver : list) {
          if( recItemConver.isConver(obj)
                  ){
              return recItemConver;
          }
        }
        throw  new ApiException(400,"转换器不存在:"+obj);
    }

    public static RecItemEntity converToItem(ESuperEntity val){
        RecItemConver recItemConver =  getRecItemConver(val);
        RecItemEntity itemEntity =  recItemConver.conver(val);
        itemEntity.setItemCode(val.getClass().getSimpleName());
        return itemEntity;
    }

    public static void asyncSaveItem(ESuperEntity val){
        CompletableFuture.runAsync(() -> {
            RecItemEntity itemEntity = converToItem(val);
            iRecItemService.save(itemEntity);
        });

    }

    @Autowired(required = false)
    public void setList(List<RecItemConver> val) {
        RecUtil.list = val;
    }

    @Autowired
    public void setiRecItemService(IRecItemService iRecItemService) {
        RecUtil.iRecItemService = iRecItemService;
    }
}
